﻿using System.Configuration;
using Learun.Ioc;
using Microsoft.Practices.Unity;

namespace Learun.DataBase.Repository
{
    /// <summary>
    /// 根据配置文件等取拿数据库信息。用于new的。只不过这里用的是IOC注入的方式，所以字眼上看不到new
    /// </summary>
    public class DbFactory
    {
        public static DatabaseType GetIDatabaseType()
        {
            return DbFactory.GetDbType(ConfigurationManager.ConnectionStrings["BaseDb"].ProviderName);
        }

        /// <summary>
        /// 默认走的是XmlConig下，database.config下的BaseDb这个节点下的字符串。
        /// 首先走Web.config，然后里面指向了Xmlconfig下的database.config
        /// </summary>
        /// <returns></returns>
        public static IDatabase GetIDatabase()
        {
            //if (!Computer.IsSameComputer())
            //{
            //	throw new Exception("该电脑没有授权，请联系管理员！");
            //}
            return DbFactory.GetIDatabaseByIoc(DbFactory.GetDbType(ConfigurationManager.ConnectionStrings["BaseDb"].ProviderName).ToString(), "BaseDb");
        }

        public static IDatabase GetIDatabase(string connString, DatabaseType dbType)
        {
            return DbFactory.GetIDatabaseByIoc(dbType.ToString(), connString);
        }

        public static IDatabase GetIDatabase(string connString, string dbType)
        {
            return DbFactory.GetIDatabaseByIoc(dbType, connString);
        }

        public static IDatabase GetIDatabase(string name)
        {
            return DbFactory.GetIDatabaseByIoc(DbFactory.GetDbType(ConfigurationManager.ConnectionStrings[name].ProviderName).ToString(), name);
        }

        /// <summary>
        /// 根据信息去注入（实例化）一个数据库连接对象
        /// </summary>
        /// <param name="name">目前有ora sql mysql</param>
        /// <param name="connString"></param>
        /// <returns></returns>
        public static IDatabase GetIDatabaseByIoc(string name, string connString)
        {
            return UnityIocHelper.Instance.GetService<IDatabase>(name, new ParameterOverride[]
            {
                new ParameterOverride("connString", connString)
            });
        }

        private static DatabaseType GetDbType(string providerName)
        {
            DatabaseType result;
            if (!(providerName == "System.Data.SqlClient"))
            {
                if (!(providerName == "MySql.Data.MySqlClient"))
                {
                    if (!(providerName == "Oracle.ManagedDataAccess.Client"))
                    {
                        result = DatabaseType.SqlServer;
                    }
                    else
                    {
                        result = DatabaseType.Oracle;
                    }
                }
                else
                {
                    result = DatabaseType.MySql;
                }
            }
            else
            {
                result = DatabaseType.SqlServer;
            }
            return result;
        }
    }
}
